package java_test.io;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Exercise4 {
    public static void main(String[] args) {
        wordCount("C:\\Users\\lemon\\Desktop\\新建文本文档.txt");
    }

    public static void wordCount(String filePath) {
        BufferedReader br = null;
        BufferedWriter bw = null;
        Map<Character, Integer> map = new HashMap<>();

        try {
            br = new BufferedReader(new FileReader(new File(filePath)));
            bw = new BufferedWriter(new FileWriter(new File("file\\text\\wordCount.txt")));

            int b = 0;
            while ((b = br.read()) != -1) {
                char ch = (char)b;
                if (!map.containsKey(ch)) {
                    map.put(ch, 1);
                } else {
                    map.put(ch, map.get(ch) + 1);
                }
            }

            Set<Map.Entry<Character, Integer>> entries = map.entrySet();

            for (Map.Entry<Character, Integer> entry : entries) {
                switch (entry.getKey()) {
                    case ' ':
                        bw.write("空格=" + entry.getValue());
                        break;
                    case '\t':
                        bw.write("tab键=" + entry.getValue());
                        break;
                    case '\r':
                        bw.write("回车键=" + entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行符" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                }
                bw.newLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
